package com.mhc.suzuki.controller;

import com.alibaba.fastjson.JSON;
import com.mhc.haval.security.model.User;
import com.mhc.suzuki.constant.ErrorCodeEnum;
import com.mhc.suzuki.dal.model.CarInfoDO;
import com.mhc.suzuki.dal.model.LoanInfoDO;
import com.mhc.suzuki.form.LoanHistoryForm;
import com.mhc.suzuki.form.LoanInfoForm;
import com.mhc.suzuki.model.bo.OrderListBO;
import com.mhc.suzuki.service.LoanInfoService;
import com.mhc.suzuki.service.OrderService;
import com.mhc.suzuki.util.BeanCopierUtil;
import com.mhc.suzuki.util.DateUtil;
import com.mhc.suzuki.vo.LoanInfoVO;
import com.mhc.suzuki.vo.OrderVO;
import com.subaru.common.entity.BizResult;
import com.subaru.common.query.PageResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * Created by kanon on 17/8/11 19:18.
 */
@Slf4j
@RestController
@RequestMapping(value = "/loaninfo")
public class LoanInfoController {

    @Autowired
    private LoanInfoService loanInfoService;

    @Autowired
    private OrderService orderService;

    /**
     * 根据订单号，角色类型获取贷款信息
     *
     * @param orderNO
     * @return
     */
    @ApiOperation(value = "根据订单号，角色类型获取贷款信息", notes = "")
    @RequestMapping(value = {"/{orderNO}"}, method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNO", paramType = "path", value = "订单号", required = true),
    })
    public BizResult<LoanInfoVO> getLoanInfoByOrderNO(@PathVariable String orderNO) {
        log.info("orderNO:{}", orderNO);

        try {
            LoanInfoVO loanInfoVO = loanInfoService.getLoanInfo(orderNO);
                return BizResult.create(loanInfoVO, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
        } catch (Exception e) {
            log.error("error in getLoanInfoByOrderNO", e);
            return BizResult.create(ErrorCodeEnum.SELECT_FAILURE.getErrCode(), ErrorCodeEnum.SELECT_FAILURE.getErrMsg());
        }
    }


    /**
     * 根据订单号新增或者更新车辆，贷款，垫资信息
     *
     * @param loanInfoForm
     * @return
     */
    @ApiOperation(value = "根据订单号新增或者更新车辆，贷款，垫资信息", notes = "")
    @RequestMapping(value = {"/"}, method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loanInfoForm", dataType = "LoanInfoForm", value = "贷款信息", required = true),
    })
    public BizResult<Boolean> addOrUpdateLoanInfoByOrderNO(@AuthenticationPrincipal User logedUser, @RequestBody LoanInfoForm loanInfoForm) {
        log.info("loanInfoForm:{}",JSON.toJSONString(loanInfoForm));
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        if (userOptional.isPresent()) {
            try {
                LoanInfoDO loanInfoDO = BeanCopierUtil.convert(loanInfoForm, LoanInfoDO.class);
                CarInfoDO carInfoDO = BeanCopierUtil.convert(loanInfoForm, CarInfoDO.class);
                carInfoDO.setCarAge(DateUtil.defaultParseStringToDateTime(loanInfoForm.getCarAge()));
                return BizResult.create(loanInfoService.addOrUpdateLoanInfoAndCarInfo(loanInfoDO, carInfoDO, logedUser.getStaffId()), ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
            } catch (Exception e) {
                log.error("error in addOrUpdateLoanInfoByOrderNO", e);
                return BizResult.create(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR.getErrCode(), ErrorCodeEnum.INSERT_OR_UPDATA_ERROR.getErrMsg());
            }
        }else {
            return BizResult.create(ErrorCodeEnum.NOT_LOGIN.getErrCode(), ErrorCodeEnum.NOT_LOGIN.getErrMsg());
        }
    }

    @ApiOperation(value = "贷款历史列表", notes = "")
    @RequestMapping(value = "/history", method = RequestMethod.GET)
    public BizResult<PageResult<OrderVO>> findOrderList(LoanHistoryForm loanHistoryForm) {
        log.info("loanHistoryForm:{}",JSON.toJSONString(loanHistoryForm));
        try {
            if (StringUtils.isBlank(loanHistoryForm.getCustomerIdCard()) && StringUtils.isBlank(loanHistoryForm.getKeyword())) {
                return BizResult.create(ErrorCodeEnum.BUYER_IDCARD_ISNULL.getErrCode(), ErrorCodeEnum.BUYER_IDCARD_ISNULL.getErrMsg());
            }
            if (loanHistoryForm.getPageNO() == null || loanHistoryForm.getPageNO() == 0) {
                loanHistoryForm.setPageNO(1);
            }
            if (loanHistoryForm.getPageSize() == null || loanHistoryForm.getPageSize() == 0) {
                loanHistoryForm.setPageSize(10);
            }
            OrderListBO orderListBO = BeanCopierUtil.convert(loanHistoryForm, OrderListBO.class);
            PageResult<OrderVO> orderVOPageResult = orderService.queryOtherOrderList(orderListBO);
            if (orderVOPageResult.getTotalPage() > 0) {
                return BizResult.create(orderVOPageResult, true, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg());
            } else {
                return BizResult.create(null, ErrorCodeEnum.NO_DATA.getErrCode(), ErrorCodeEnum.NO_DATA.getErrMsg());
            }
        } catch (Exception e) {
            log.error("Query order list exception: ", e);
            return BizResult.create(null, ErrorCodeEnum.SELECT_FAILURE.getErrCode(), ErrorCodeEnum.SELECT_FAILURE.getErrMsg());
        }
    }


}